package com.ibm.portlet.mvc;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.portlet.ModelAndView;

@Controller
@RequestMapping("VIEW")
public class PersonController {

	@RequestMapping(params = "action=person")
	public void action(ActionRequest request, ActionResponse response,
			Person person, Errors errors, SessionStatus sessionStatus) {
		ValidationUtils.rejectIfEmpty(errors, "firstName", "firstName.empty",
				"Please, fill in your first name");
		ValidationUtils.rejectIfEmpty(errors, "lastName", "lastName.empty",
				"Please, fill in your last name");
		if (!errors.hasErrors()) {
			// done. We could/should call sessionStatus.setComplete()
			// but let's keep the person in the session for the next render

			response.setRenderParameter("action", "hello");
		}
	}

	@RequestMapping(params = "action=person")
	public ModelAndView renderForm(RenderRequest request, ModelMap modelMap) {
		return new ModelAndView("/WEB-INF/jsp/person.jsp");
	}

	@RequestMapping(params = "action=hello")
	public ModelAndView renderGreeting(RenderRequest request) {
		return new ModelAndView("/WEB-INF/jsp/hello.jsp");
	}

	@RequestMapping
	public ModelAndView renderFormFirst(RenderRequest request) {
		ModelAndView modelAndView = new ModelAndView("/WEB-INF/jsp/person.jsp");
		Person person = new Person();
		// initialize from model...
		person.setFirstName("John");
		modelAndView.addObject("person", person);
		return modelAndView;
	}
}
